<template>
	<Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
		<el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
			<el-form-item label="所属社区" prop="commId">
				<el-tree-select v-model="formData.commId" :data="communityTree" :props="defaultProps" check-strictly default-expand-all placeholder="请选择所属社区" value-key="id" />
			</el-form-item>
			<el-form-item label="房屋名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入房屋名称" />
			</el-form-item>
			<el-form-item label="房屋简称" prop="shortName">
				<el-input v-model="formData.shortName" placeholder="房屋简称" />
			</el-form-item>
			<el-form-item label="地址编码" prop="addrCode">
				<el-input v-model="formData.addrCode" placeholder="请输入地址编码" />
			</el-form-item>
			<el-form-item label="显示排序" prop="sort">
				<el-input v-model="formData.sort" placeholder="显示排序" />
			</el-form-item>
			<el-form-item label="扩展属性" prop="extendAttrs">
				<el-checkbox-group v-model="switchCodeValue">
					<template :key="index" v-for="(item, index) in getIntDictOptions(DICT_TYPE.EXTEND_ATTRS)">
						<el-checkbox v-if="item.label != '待定'" :false-label="0" :label="item.label" :value="item.value" border :key="index" style="margin: 0 10px 10px 0" />
					</template>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="外系统-关联ID" prop="cloudLinkId">
				<el-input v-model="formData.cloudLinkId" placeholder="请输入外系统-关联ID" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button type="primary" @click="submitForm">确 定</el-button>
			<el-button @click="dialogVisible = false">取 消</el-button>
		</template>
	</Dialog>
</template>
<script lang="ts" setup>
	import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
	import { defaultProps, handleTree } from '@/utils/tree'
	import * as HouseRoomApi from '@/api/zwsj/houseRoom'
	import * as CommunityApi from '@/api/zwsj/community'

	defineOptions({ name: 'HouseForm' })

	const { t } = useI18n() // 国际化
	const message = useMessage() // 消息弹窗

	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		commId: undefined,
		parentId: 0,
		addrCode: undefined,
		name: undefined,
		shortName: undefined,
		sort: undefined,
		cloudLinkId: undefined,
		extendAttrs: undefined,
	})
	const formRules = reactive({
		commId: [
			{
				required: true,
				message: '社区不能为空',
				trigger: 'blur',
			},
		],
		name: [
			{
				required: true,
				message: '房屋名称不能为空',
				trigger: 'blur',
			},
		],
		shortName: [
			{
				required: true,
				message: '房屋简称不能为空',
				trigger: 'blur',
			},
		],
		sort: [
			{
				required: true,
				message: '序号不能为空',
				trigger: 'blur',
			},
		],
	})
	const formRef = ref() // 表单 Ref
	const communityTree = ref() // 树形结构
	const switchCodeValue = ref([])

	/** 打开弹窗 */
	const open = async (type: string, id?: number, commId?: number) => {
		dialogVisible.value = true
		dialogTitle.value = t('action.' + type)
		formType.value = type
		resetForm()

		//设置区域默认值
		formData.value.commId = commId
		// 修改时，设置数据
		if (id) {
			formLoading.value = true
			try {
				if (type === 'update') {
					formData.value = await HouseRoomApi.getHouseRoom(id)
					//设置多选框值
					let extendAttr = formData.value.extendAttrs || ''
					if ('' !== extendAttr) {
						let checkedArray = extendAttr.split('')
						checkedArray.forEach((e, idx) => {
							if (parseInt(e) > 0) {
								switchCodeValue.value.push(idx)
							}
						})
					}
				}
			} finally {
				formLoading.value = false
			}
		}
		// 获得社区树
		await getTree()
	}
	defineExpose({ open }) // 提供 open 方法，用于打开弹窗

	/** 提交表单 */
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
	const submitForm = async () => {
		// 校验表单
		if (!formRef) return
		const valid = await formRef.value.validate()
		if (!valid) return
		// 提交请求
		formLoading.value = true
		try {
			const data = formData.value as unknown as HouseRoomApi.HouseRoomVo

			//构建扩展数据
			let extendAttrList = getIntDictOptions(DICT_TYPE.EXTEND_ATTRS)
			data.extendAttrs = ''
			extendAttrList.map((item, idx) => {
				if (switchCodeValue.value.includes(idx)) {
					data.extendAttrs += '1'
				} else {
					data.extendAttrs += '0'
				}
			})

			if (formType.value === 'create') {
				await HouseRoomApi.createHouseRoom(data)
				message.success(t('common.createSuccess'))
			} else {
				await HouseRoomApi.updateHouseRoom(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			commId: undefined,
			parentId: 0,
			addrCode: undefined,
			name: undefined,
			shortName: undefined,
			sort: undefined,
			cloudLinkId: undefined,
			extendAttrs: undefined,
		}
		formRef.value?.resetFields()
		switchCodeValue.value = []
	}

	/** 获得区域树 */
	const getTree = async () => {
		communityTree.value = []
		const data = await CommunityApi.listSimpleCommunitys()
		let community: Tree = { id: 0, name: '顶级区域', children: [] }
		community.children = handleTree(data)
		communityTree.value.push(community)
	}
</script>
